#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <hiredis.h>
#include <QThreadPool>
#include <myrunable.h>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//    conRedis();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    qDebug()<<"start working";
    startWorking();
}

void MainWindow::on_pushButton_2_clicked()
{
    foreach (MyRunable * runTask, threadList) {
        runTask->stopSend();

    }
    qDebug()<<"stop";
}

void MainWindow::conRedis()
{
    // 连接Redis
    context = redisConnect("127.0.0.1", 6379);
    if (context == nullptr || context->err) {
        if (context) {
            qDebug() << "Error: " << context->errstr;
            redisFree(context);
        } else {
            qDebug() << "Can't allocate redis context";
        }
    }else{
        qDebug()<<"connection success";
        //        // 设置一个键值对
        //        redisCommand(context, "SET key1 %s", "Hello, Redis!");

        //        // 获取键值对
        //        redisReply *reply = (redisReply *)redisCommand(context, "GET key1");
        //        if (reply->type == REDIS_REPLY_STRING) {
        //            qDebug() << "key1:" << reply->str;
        //        }

        //        // 释放内存
        //        freeReplyObject(reply);
        //        redisFree(context);
    }
}

void MainWindow::startWorking()
{
    QThreadPool* pool = QThreadPool::globalInstance();
    int total = 10000;
    int threadCount = 4;
    int batchSize = total / threadCount;

    // 为每个线程创建Redis连接（hiredis不支持线程安全的连接共享）
    for (int i = 0; i < threadCount; ++i) {
        redisContext* ctx = redisConnect("127.0.0.1", 6379);
        if (ctx && ctx->err) {
            // 错误处理
            continue;
        }

        int startId = i * batchSize;
        runThread = new MyRunable(startId, batchSize, ctx);
        threadList.append(runThread);
        pool->start(runThread);
    }
}
